#include "stdio.h"
#include "signal.h"
#include <sys/stat.h>
static void sigHandler(int no)
{
    printf("sigHandler %d\n", no);
}
#ifndef __UCLIBC__
#define TRACE_MAX_NUM		16
#endif

/**
 * ak_dump: dupm stack info when caught appointed signal
 * @signal_no[IN]: signal no.
 * @return: none
 * notes: handle signal: SIGINT, SIGTERM, SIGSEGV
 */
static void ak_dump(int signal_no)
{
	printf("\n**************************\n");
	printf("[%s]: signal %d caught\n", __func__, signal_no);
	printf("**************************\n");

#ifndef __UCLIBC__
    if (SIGINT != signal_no) {
        int ii = 0;
    	void *tracePtrs[TRACE_MAX_NUM];
    	int count = backtrace(tracePtrs, TRACE_MAX_NUM);
    	char **funcNames = backtrace_symbols(tracePtrs, count);
    	for(ii = 0; ii < count; ii++)
    	{
    		printf("%s\n", funcNames[ii]);
    	}
    	free(funcNames); // free_my
    }
#endif

	fflush(stderr);
	fflush(stdout);

	if(SIGSEGV == signal_no) {
    	exit(1);
    }
}

static void
handler(int sig, siginfo_t *info, void *ucontext)
{
    printf("handler %d\n", sig);
    ak_dump(sig);
}
int main()
{
    // 新增sigaction配置
    /*
     struct sigaction {
               void     (*sa_handler)(int);
               void     (*sa_sigaction)(int, siginfo_t *, void *);
               sigset_t   sa_mask;
               int        sa_flags;
               void     (*sa_restorer)(void);
           };
    */
    struct sigaction sa;
    struct sigaction oldSa;
    sigemptyset(&sa.sa_mask);
    #if 0
    sa.sa_handler = sigHandler;
    sa.sa_flags = SA_RESTART;  // 允许系统调用自动重启
    #else
    sa.sa_flags = SA_RESTART|SA_SIGINFO;  // 允许系统调用自动重启
    sa.sa_sigaction = handler;
    #endif
       
    if (sigaction(SIGINT, &sa, &oldSa) == -1) {
        perror("sigaction error");
        return 1;
    }
    if (sigaction(SIGUSR1, &sa, &oldSa) == -1) {
        perror("sigaction error");
        return 1;
    }

    while (1) {
        usleep(1000*1000);
    }
    return 0;
}